package com.zj;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * 最佳匹配任务类
 */

public class BestMatchingTask implements Callable<BestMatchingData> {
    private String word;  //要匹配的单词
    private List<String> words;  //词库
    private int startIndex;  //起始位置
    private int endIndex;  //结束位置

    private CountDownLatch latch;

    public BestMatchingTask(String word, List<String> words, int startIndex, int endIndex) {
        this.word = word;
        this.words = words;
        this.startIndex = startIndex;
        this.endIndex = endIndex;
    }

    public BestMatchingTask(String word, List<String> words, int startIndex, int endIndex,CountDownLatch latch) {
        this.word = word;
        this.words = words;
        this.startIndex = startIndex;
        this.endIndex = endIndex;
        this.latch=latch;
    }

    @Override
    public BestMatchingData call() throws Exception {
        List<String> minDistanceWords=new ArrayList<>();  //最短距离 的单词列表
        int minDistance=Integer.MAX_VALUE;  //最短距离
        int distance; //计算的距离
        //循环words集合 从 startIndex 到 endIndex,计算  word 与这些单词之间的编辑距离
        for (int i = startIndex; i <= endIndex; i++) {
            //添加的新功能
            String sameword=DeleteSameWord.findMaxWord(word,words.get(i));
            String newword1=word.replaceFirst(sameword,"");
            String newword2=words.get(i).replaceFirst(sameword,"");


            //记录最小的编辑距离 及 对应的单词之间的编辑距离
//            distance=EditDistance.calculate(word,words.get(i));
            distance=EditDistance.calculate(newword1,newword2);
            //找到更短的编辑距离
            if(distance<minDistance){
                minDistanceWords.clear(); //先清空集合
                minDistance=distance;   //更新最短距离
                minDistanceWords.add(words.get(i));  //存最新 的最短距离的单词列表到集合
            }else if(distance==minDistance){
                minDistanceWords.add(words.get(i));
            }
        }

        //将最小的编辑距离 及 对应的单词之间的编辑距离  封装到一个对象中
        BestMatchingData result=new BestMatchingData();
        result.setDistance(minDistance);
        result.setWords(minDistanceWords);
        return result;
    }
}
